﻿using System;
using System.IO;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using Forms = System.Windows.Forms;

using LibreTimeTracker.Library;
using System.Drawing;

namespace LibreTimeTracker
{
  /// <summary>
  /// Interaction logic for MainWindow.xaml
  /// </summary>
  public partial class MainWindow : Window
  {
    private readonly Uri URIBASE_RESOURCES = new Uri("pack://application:,,,/LibreTimeTracker;component");
    private Forms.NotifyIcon NotifyIcon = new Forms.NotifyIcon();

    public MainWindow()
    {
      InitializeComponent();

      InitNotifyIcon();
    }

    private void InitNotifyIcon()
    {
      //NotifyIcon = new Forms.NotifyIcon();
      Stream iconStream = Application.GetResourceStream(new Uri(URIBASE_RESOURCES, "Resources/Logo.ico")).Stream;
      NotifyIcon.Icon = new System.Drawing.Icon(iconStream);
      NotifyIcon.ContextMenuStrip = new NotifyIconMenuStrip(this, ToggleWindow);
      NotifyIcon.MouseDoubleClick += new Forms.MouseEventHandler(NotifyIcon_MouseDoubleClick);
      NotifyIcon.MouseClick += new Forms.MouseEventHandler(NotifyIcon_MouseClick);

      //NotifyIcon.BalloonTipTitle = "Minimize to Tray App";
      //NotifyIcon.BalloonTipText = "You have successfully minimized your form.";

      NotifyIcon.Visible = true;
      //NotifyIcon.ShowBalloonTip(500);
    }

    private void NotifyIcon_MouseDoubleClick(object sender, Forms.MouseEventArgs e)
    {
      ToggleWindow();
    }

    private void NotifyIcon_MouseClick(object sender, Forms.MouseEventArgs e)
    {
      ((NotifyIconMenuStrip)NotifyIcon.ContextMenuStrip).UpdateMenuItems();
    }

    private void Window_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
    {
      this.DragMove();
    }

    private void ToggleWindow()
    {
      if (this.WindowState == WindowState.Minimized)
      {
        this.Show();
        this.WindowState = WindowState.Normal;
      }
      else
      {
        this.Hide();
        this.WindowState = WindowState.Minimized;
      }
    }

    private void btnMinimize_Click(object sender, RoutedEventArgs e)
    {
      ToggleWindow();
    }

    private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e)
    {
      if (NotifyIcon != null)
      {
        NotifyIcon.Visible = false;
        NotifyIcon.Dispose();
      }
    }
  }
}
